<?php namespace Home\Controller;

use Hdphp\Controller\Controller;

class ListController extends Controller{
	private $gmodel;
	private $cmodel;
	private $spmodel;
	private $nmodel;
	public function __init(){
//		实例化商品模型
		$this->gmodel= new\Common\Model\Goods;
//		实例化分类模型
		$this->cmodel=new\Common\Model\Cate;
//		实例化商品属性模型
		$this->spmodel=new\Common\Model\Shopnature;
//		实例化类型属性模型
		$this->nmodel=new \Common\Model\Nature;
	}
	
	
	public function index(){
//		获取顶级分类
		$topCate=$this->cmodel->where('pid=0')->limit(5)->get();
		View::with('topCate',$topCate);
		$gdata=$this->gmodel->get();
//		p($gdata);
		View::with('gdata',$gdata);
//		根据当前的cid获得对应的商品的gid
		$gids=$this->cidGetGids(Q('get.cid',0,'intval'));
//		p($gids);exit;
//		2.根据gid找到商品属性
		$goodsAttr=$this->gidGetAttr($gids);
		View::with('goodsAttr',$goodsAttr);
//		p($goodsAttr);
		//3.处理筛选参数param 0_0_.....
		$num = count($goodsAttr);
		$param = isset($_GET['param']) ? explode('_', $_GET['param']) : array_fill(0, $num, 0);
		View::with('param',$param);
		//4.通过param参数筛选商品gid
		$resultGids = $this->filter($param,$gids);
//		p($param);
		View::make();
		
	}

	private function filter($param,$cidGids){
		$gids=array();
		foreach ($param as $gtid){
			if($gtid){
//				1，找到shopvalue比如找到红色
				$gtvalue=$this->spmodel->where("sid={$gtid}")->pluck('shopvalue');
				
//				2.通过 红色 找到对应的商品id
				$gids[]=$this->spmodel->where("shopvalue='{$gtvalue}'")->lists('goods_gid');
//				p($gids);exit;
			}
		}
		//如果点击了“不限”之外的属性
		if($gids){
			//取交集
			$gidsTemp = $gids[0];
			foreach ($gids as $v) {
				$gidsTemp = array_intersect($gidsTemp, $v);
			}
			//和当前分类对应的gid再次取交集
			return array_intersect($gidsTemp, $cidGids);
		}else{//如果是全部是“不限”的时候
			return $cidGids;
		}		
	}


//	通过gid获得商品属性
	private function gidGetAttr($gids){
		$data=$this->spmodel->where("goods_gid in(" . implode(',', $gids) . ")")->groupBy('shopvalue')->get();
//		p($data);die;
//		把相同类型属性id的归纳在一起
		$sameAttr=array();
		foreach ($data as $v){
			$sameAttr[$v['nature_nid']][]=$v;
		}
//p($sameAttr);
//		组合数组
		$temp=array();
		foreach ($sameAttr as $nid=> $v){
			$temp[]=array(
			 'name'=>$this->nmodel->where("nid={$nid}")->pluck('naname'),
			 'value'=>$v
			);
		}
//		p($temp);
		return $temp;
		
	}


//	通过cid获得gid
	private function cidGetGids($cid){
//		通过当前的cid获得对应的所有的子集cid
		$cids = $this->getSonCids($this->cmodel->get(),$cid);
//		p($cids);exit;
		$cids[] = $cid;
		//2.通过子集cid查找对应的商品的gid
		$gids =$this->gmodel->where("classify_cid in(" . implode(',', $cids) . ")")->lists('gid');
		return $gids;
	}

	
	//递归获得指定cid的所有子集
	private function getSonCids($data,$cid){
		$temp = array();
		foreach ($data as $v) {
			if($v['pid'] == $cid){
				$temp[] = $v['cid'];
				$temp = array_merge($temp,$this->getSonCids($data, $v['cid']));
			}
		}
		return $temp;
	}
}






















 ?>